<?php

namespace App\Http\Controllers;

use App\Events\LoginUserEvent;
use App\Http\Requests\AuthRequests\AnswerRequest;
use App\Http\Requests\AuthRequests\AvatarRequest;
use App\Http\Requests\AuthRequests\PasswordRequest;
use App\Http\Requests\AuthRequests\EmailRegisterRequest;
use App\Http\Requests\AuthRequests\PhoneRegisterRequest;
use App\Http\Requests\AuthRequests\PhoneFindRequest;
use App\Http\Requests\AuthRequests\EmailFindRequest;
use App\Http\Requests\AuthRequests\LoginRequest;
use App\Http\Requests\AuthRequests\PayPasswordRequest;
use App\Http\Requests\AuthRequests\PayPassword1Request;
use App\Http\Requests\AuthRequests\RegisterRequest;
use App\Http\Resources\AuthResources\AnswerResource;
use App\Http\Resources\AuthResources\InviteResource;
use App\Http\Resources\AuthResources\ProblemResource;
use App\Http\Resources\AuthResources\UserInfoResource;
use App\Models\Account;
use App\Models\AccountLog;
use App\Models\AppVersion;
use App\Models\Coin;
use App\Models\Device;
use App\Models\Leader;
use App\Models\PasswordAnswer;
use App\Models\PasswordProblem;
use App\Models\Property;
use App\Models\Setting;
use App\Models\User;
use Hashids\Hashids;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class AuthController extends Controller
{

    public function emailRegister(EmailRegisterRequest $request)
    {

//        $parent_id = (new Hashids(config('hashids.HASHID_SALT'), config('hashids.HASHID_NUMBER')))->decode($request->input('parent_id'));
//
//
//        if (!$parent_id || !User::where('id', $parent_id[0])->exists()) {
//            $this->error(1116);
//        }

        $user = new User();
        $user->username = strtolower($request->input('email'));
        $user->email = strtolower($request->input('email'));
        $user->password = Hash::make($request->input('password'));
        $user->pay_password = Hash::make($request->input('pay_password'));
        $parentUser = User::where('invitation_code', $request->input('invitation_code'))->first();
        if (!$parentUser) {
            $this->error(500, '无效的邀请码');
        }
        $user->parent_id = $parentUser->id;
        $coins = Coin::where('id', 2)->get();

        try {
            Cache::lock('register', 10)->get(function () use ($coins, $user) {
                DB::transaction(function () use ($coins, $user) {
                    $user->save();

//                    if ($user->parent_id) {
//                        User::find($user->parent_id)->appendNode($user);
//                    }

                    $user->invitation_code = 'XG' . ($user->id + 10000);
                    $user->save();

                    foreach ($coins as $coin) {
                        $account = new Account();
                        $account->coin_id = $coin->id;
                        $account->user_id = $user->id;
                        $account->save();
                    }
                });
            });
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
            $this->error(500);
        }

        return $this->array([
            'download_url' => AppVersion::value('download_url')
        ]);
    }
    /**
     * 注册.
     * @param RegisterRequest $request
     * @return Response
     */
    public function phone_find(PhoneFindRequest $request)
    {
        $user = User::where('username', $request->input('mobile'))->first();
        if (!$user) {
            $this->error(1002);
        }
        if (
            $request->input('password')
            != $request->input('password1')
        ) {
            $this->error(1015);
        }
        $user->password = Hash::make($request->input('password'));

        $user->save();

        return $this->null();
    }
    /**
     * 注册.
     * @param RegisterRequest $request
     * @return Response
     */
    public function email_find(EmailFindRequest $request)
    {
        $user = User::where('username', $request->input('email'))->first();
        if (!$user) {
            $this->error(1002);
        }
        if (
            $request->input('password')
            != $request->input('password1')
        ) {
            $this->error(1015);
        }

        $user->password = Hash::make($request->input('password'));

        $user->save();

        return $this->null();
    }
    /**
     * 注册.
     * @param RegisterRequest $request
     * @return Response
     */
    public function PhoneRegister(PhoneRegisterRequest $request)
    {
//        $parent_id = (new Hashids(config('hashids.HASHID_SALT'), config('hashids.HASHID_NUMBER')))->decode($request->input('parent_id'));
//
//        if (!$parent_id || !User::where('id', $parent_id[0])->exists()) {
//            $this->error(1116);
//        }

        $user = new User();
        $user->username = $request->input('mobile');
        $user->mobile = $request->input('mobile');
        $user->password = Hash::make($request->input('password'));
        $user->pay_password = Hash::make($request->input('pay_password'));
//        $user->parent_id = $parent_id[0];
        $parentUser = User::where('invitation_code', $request->input('invitation_code'))->first();
        if (!$parentUser) {
            $this->error(500, '无效的邀请码');
        }
        $user->parent_id = $parentUser->id;
        $coins = Coin::where('id', 2)->get();

        try {
            Cache::lock('register', 10)->get(function () use ($coins, $user) {
                DB::transaction(function () use ($coins, $user) {
                    $user->save();
//                    if ($user->parent_id) {
//                        User::find($user->parent_id)->appendNode($user);
//                    }
                    $user->invitation_code = 'XG' . ($user->id + 10000);
                    $user->save();
                    foreach ($coins as $coin) {
                        $account = new Account();
                        $account->coin_id = $coin->id;
                        $account->user_id = $user->id;
                        $account->save();
                    }
                });
            });
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
            $this->error(500);
        }

        return $this->array([
            'download_url' => AppVersion::value('download_url')
        ]);
    }

    /**
     * 登录.
     * @param LoginRequest $request
     * @return mixed
     */
    public function login(LoginRequest $request)
    {
        $loginField = $request->input('username');
        $password = $request->input('password');

        $user = User::where('username', $loginField)->first();
        if (!$user) {
            $this->error(1002);
        }
        if ($user->status != 0) {
            $this->error(1003);
        }
        if (Hash::check($password, $user->password)) {
            $token = auth()->login($user);
            event(new LoginUserEvent($user));
            return $this->array(compact('token'));
        } else {
            $this->error(1002);
        }
    }

    /**
     * 退出.
     * @return mixed
     */
    public function logout()
    {
        Auth::logout();

        return $this->null();
    }
    /**
     * 修改交易密码第一步.
     *
     * @param PayPasswordRequest $request
     * @return Response
     */
    public function modiPayPwd(PayPassword1Request $request)
    {
        /** @var User $user */
        $user = Auth::user();

        if (
            $request->input('pay_password')
            != $request->input('pay_password1')
        ) {
            $this->error(1011);
        }

        $user->pay_password = Hash::make($request->input('pay_password'));
        $user->save();

        return $this->null();
    }

    /**
     * 修改交易密码第一步.
     *
     * @param PayPasswordRequest $request
     * @return Response
     */
    public function setPayPwd(PayPasswordRequest $request)
    {
        /** @var User $user */
        $user = Auth::user();
        if (!$user->pay_password) {
            $this->error(1011);
        }
        if (
            $request->input('new_pay_password')
            != $request->input('new_pay_password1')
        ) {
            $this->error(1011);
        }


        $user->pay_password = Hash::make($request->input('new_pay_password'));
        $user->save();

        return $this->null();
    }

    /**
     * 修改密码
     * @param DoPayPasswordRequest $request
     * @return Response
     */
    public function setPwd(PasswordRequest $request)
    {
        /** @var User $user */
        $user = Auth::user();
        if (!$user->password) {
            $this->error(1011);
        }
        if (
            $request->input('new_password')
            != $request->input('new_password1')
        ) {
            $this->error(1011);
        }


        $user->password = Hash::make($request->input('new_password'));
        $user->save();

        return $this->null();
    }

    /**
     * 用户信息
     *
     * @return UserInfoResource
     */
    public function userInfo()
    {
        $user = Auth::user();

        return new UserInfoResource($user);
    }

    /**
     * 设置头像.
     *
     * @param AvatarRequest $request
     * @return Response
     */
    public function avatar(AvatarRequest $request)
    {
        /** @var User $user */
        $user = Auth::user();
        $user->avatar = $request->input('avatar');
        $user->save();

        return $this->null();
    }

    /**
     * 参数配置
     *
     * @return AnonymousResourceCollection
     */
    public function setting()
    {
        // 更新兑换价格
        $redis = Redis::connection();
        $ticker = $redis->get('etf:ticker:ET/USDT');
        if ($ticker) {
            Setting::where('key', 'ytb_price')->update(['value' => bcadd(json_decode($ticker, true)['close'], 0, 4)]);
        }

        $arr = [];
        Setting::select('key', 'value', 'explain', 'remark')
            ->whereIn('key', ['dse_price', 'dse_name'])
            ->get()
            ->each(function ($setting) use (&$arr) {
                $arr[$setting->key] = $setting;
            });

        return $this->array($arr);
    }


    /**
     * 邀请好友（列表）.
     * @param Request $request
     * @return AnonymousResourceCollection
     */
    public function poolList(Request $request)
    {
        $per_page = $request->input('per_page', 15);
        $users = User::where('parent_id', Auth::id())
            ->orderBy('id', 'desc')
            ->paginate($per_page);

        return InviteResource::collection($users);
    }
}
